package com.jichangxiu.flow.server.core.entity.Bo;

import cn.hutool.core.util.ObjectUtil;
import com.jichangxiu.flow.server.core.context.LiteFlowContext;
import com.jichangxiu.flow.server.core.enums.ProcessEnums;
import com.jichangxiu.flow.server.core.utils.ElUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ElBo:
 *
 * @author Jcx
 * @create 2025-01-01 00:00:00
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ElBo {

    private LiteFlowContext liteFlowContext;

    private ProcessBo mainProcessBo;

    private List<ProcessBo> commonProcessBoList;

    private List<String> commonProcessBrotherIdList;

    private List<ProcessBo> cycleProcessBoList;

    private List<String> cycleProcessBrotherIdList;

    public static ElBo buildElBo(LiteFlowContext liteFlowContext, List<ProcessBo> processBoList) {
        List<ProcessBo> mainProcessBoList = processBoList.stream().filter(linkBo -> linkBo.getType().equals(ProcessEnums.MAIN.name())).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(mainProcessBoList) || mainProcessBoList.size() != 1)
            throw new RuntimeException("流程中必须且只能有一个主流程");
        List<ProcessBo> commonProcessBoList = processBoList.stream().filter(linkBo -> linkBo.getType().equals(ProcessEnums.COMMON.name())).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(commonProcessBoList)) commonProcessBoList = new ArrayList<>();
        List<ProcessBo> cycleProcessBoList = processBoList.stream().filter(linkBo -> linkBo.getType().equals(ProcessEnums.CYCLE.name())).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(cycleProcessBoList)) cycleProcessBoList = new ArrayList<>();
        return new ElBo(liteFlowContext, mainProcessBoList.get(0), commonProcessBoList, commonProcessBoList.stream().map(ProcessBo::getBrotherId).collect(Collectors.toList()), cycleProcessBoList, cycleProcessBoList.stream().map(ProcessBo::getBrotherId).collect(Collectors.toList()));
    }

    public String toElString() {
        return ElUtils.buildEl(this);
    }

}
